package filter;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;

@WebFilter("/*")
public class SessionFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String uri = req.getRequestURI();
        // 不过滤的页面
        if (uri.endsWith("index.jsp") || uri.endsWith("LoginServlet") || uri.contains("css") || uri.contains("js")) {
            chain.doFilter(request, response);
            return;
        }
        // 获取 Session
        HttpSession session = req.getSession();
        Object student = session.getAttribute("student");
        Object isAdmin = session.getAttribute("isAdmin");

        if (student != null) {
            // 已登录的学生用户不允许访问 index.jsp
            if (uri.endsWith("index.jsp") || uri.endsWith("LoginServlet")) {
                resp.sendRedirect("GroupServlet");
                return;
            }
        } else if (isAdmin != null && (boolean) isAdmin) {
            // 管理员用户
            if (uri.endsWith("admin.jsp") || uri.endsWith("AdminServlet")) {
                chain.doFilter(request, response);
                return;
            }
        } else {
            // 未登录用户尝试访问其他页面，重定向到 index.jsp
            if (!uri.endsWith("index.jsp") && !uri.endsWith("LoginServlet")) {
                resp.sendRedirect("index.jsp");
                return;
            }
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

    public void destroy() {
    }
}
